import { useEffect, useRef, useState } from "react";
import { Container } from "react-bootstrap";
import { Form, Button } from "react-bootstrap";
import api from "../request";
import { useNavigate, useSearchParams } from "react-router-dom";
import PoemList from "../Component/PoemList";
import PaginationBar from "../Component/PaginationBar";

const PAGE_SIZE = 20;

function SearchBox({ keyword }) {
    const input = useRef(null);
    const navigate = useNavigate();

    const search = () => navigate(`/search?keyword=${input.current.value}`);
    return (
        <Form className="d-flex justify-content-center" onSubmit={(e) => {
            console.log(e);
            e.preventDefault();
            search();
        }}>
                <Form.Group controlId="searchBox" className="col-sm-10 col-lg-5">
                    <Form.Control ref={input} type="text" placeholder="请输入关键字" defaultValue={keyword} />
                </Form.Group>
                <Button className="ms-4" type="submit" style={{ minWidth: '2em' }}>搜索</Button>

        </Form>
    );
}

/**
 * 诗词列表页面
 */
function SearchPage() {
    let [searchParams, setSearchParams] = useSearchParams();
    const [poems, setPoems] = useState(null);
    const [currentPage, setCurrentPage] = useState(0);
    const [totalPages, setTotalPages] = useState(0);
    const [keyword, setKeyword] = useState('');

    const navigate = useNavigate();

    useEffect(() => {
        let page = searchParams.get('page') ? parseInt(searchParams.get('page')) : 0;
        let keyword = searchParams.get('keyword');
        if (!keyword) 
            return;
        setKeyword(keyword);

        api.searchPoems({
            keyword: keyword,
            page: page,
            size: PAGE_SIZE
        }, (err, data, _) => {
            if (err) throw err;
            setPoems(data.data.list);
            setTotalPages(data.data.totalPage);
            setCurrentPage(page);
        });
    }, [searchParams]);

    function gotoPage(page) {
        // navigate(`/poem?page=${page}`)
        setSearchParams({ page: page, keyword: keyword });
        // setCurrentPage(page);
        window.scrollTo(0, 0);
        
    }

    // TODO 没有结果时不应该显示分页组件
    if (keyword) {
        return (
            <Container>
                <h1>搜索</h1>
                <SearchBox keyword={keyword} />
                <PoemList poems={poems} />
                
                <br />
                {poems?.length !== 0 && 
                <PaginationBar
                    currentPage={currentPage}
                    totalPages={totalPages}
                    gotoPageCallback={gotoPage}
                />}
            </Container>
        );
    } else {
        return (
            <Container>
                <h1>搜索</h1>
                <SearchBox keyword={keyword} />
            </Container>
        );
    }
}

export default SearchPage;